package com.ahs.service.impl;

import com.ahs.annotation.CacheClear;
import com.ahs.annotation.Lock;
import com.ahs.mapper.UserMapper;
import com.ahs.pojo.User;
import com.ahs.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author riven zhang
 * @since 2021-04-27
 */
@Service
@Slf4j
@CacheClear
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static List<User> list;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private final static String AGE_LOCK = "AGE_LOCK";

    @Override
    public List<User> fuzzySearch(String keyword) {

        return findMemory(keyword);
    }

    private List<User> findMemory(String keyword) {
        if (CollectionUtils.isEmpty(list)) {
            log.info("集合为空，在数据库中查询");
            list = baseMapper.getAllName();
        }
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        if (keyword == null) {
            return list.stream().limit(50).collect(Collectors.toList());
        }
        return list.stream().filter(user -> StringUtils.containsIgnoreCase(user.getName(), keyword)).limit(50)
                .collect(Collectors.toList());
    }

    public static void clear() {
        list = null;
    }

    @Override
    public boolean save(User user) {
        return super.save(user);
    }

    @Override
    @Lock(AGE_LOCK)
    public boolean subtractAge(int num) {
        User user = getById(1);
        try {
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (user.getAge() >= num) {
            baseMapper.subtractAge(num);
            return true;
        }
        log.info("库存不足，当前线程：" + Thread.currentThread().getName());
        return false;
    }

}
